﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Configuration;

namespace Enter.Services
{
    public class Unity
    {
        /// <summary>
        /// 容器对象（里面可以有N个子容器）
        /// </summary>
        private static IUnityContainer container;

        /// <summary>
        /// 将 一个section配置段 注册到容器成为默认段
        /// </summary>
        /// <param name="sectionName">sectionName</param>
        /// <returns></returns>
        public static IUnityContainer Register(string sectionName)
        {
            container = new UnityContainer();
            //sectionName = Vancl.VStar.Common.sectionConfig.sectionGroupName + sectionName;
            var unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection(sectionName);

            //var unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection(sectionName);
            unitySection.Configure(container);

            return container;
        }

        /// <summary>
        /// 将 一个sectionName配置段 注册到containerName的子容器中
        /// </summary>
        /// <param name="sectionName"></param>
        /// <param name="containerName"></param>
        /// <returns></returns>
        public static IUnityContainer Register(string sectionName, string containerName)
        {
            container = new UnityContainer();
            var unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection(sectionName);
            unitySection.Configure(container, containerName);

            return container;
        }

        /// <summary>
        /// 获取默认section段中的配置对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetInstance<T>()
        {
            return container.Resolve<T>();
        }

        /// <summary>
        /// 得到容器中某一个section段中的对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="containerName">子容器名称</param>
        /// <returns></returns>
        public static T GetInstance<T>(string containerName)
        {
            return container.Resolve<T>(containerName);
        }

    }
}
